﻿// GMM_Test.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <stdio.h>
#include <iostream>
#include "opencv2/opencv.hpp"
#include"opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include"opencv2/xfeatures2d.hpp"
using namespace cv;
using namespace std;

Mat frame;
int FRAME = 0;
string b = ".jpg";
char keyboard;
Ptr<BackgroundSubtractor> pMOG2;
Mat fgMaskMOG2;

void drawRect(Mat MOG2, Mat frame);

void drawRect(Mat MOG2, Mat frame)
{
	vector<vector<Point>> contours;
	vector<Vec4i> hierarchy;
	string strArea;  // 定义字符串型变量
	findContours(MOG2, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point());
	Mat Contours = Mat::zeros(MOG2.size(), CV_8UC1);
	vector<vector<Point>> approxPoint(contours.size());
	for (int i= 0; i < contours.size(); i++)
	{
		if (contourArea(contours[i]) > 500)
		{
			Rect recPoint = boundingRect(contours[i]);
			stringstream ss;
			ss << contourArea(contours[i]);
			ss >> strArea;
			cout << "行人的坐标X: " << recPoint.x << "y:"<<recPoint.y <<"行人目标的面积： " << strArea << endl;
			rectangle(frame, recPoint,Scalar(0, 0, 255), 1);
			putText(frame, strArea, Point(recPoint.x, recPoint.y), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0xff, 0));
		}
	}
	imshow("移动目标跟踪", frame);
	FRAME++;
	stringstream ss;
	ss << FRAME << b;
	imwrite(ss.str(), frame);

}

int main()
{
	VideoCapture video("F:\\AI\\Course\\Chapter4\\vtest.avi");
	int frameNum = 1;
	if (!video.isOpened())		
		cout << "fail to open!" << endl;	
	//cout<<video.isOpened();	
	pMOG2 = createBackgroundSubtractorMOG2();
	double totalFrameNumber = video.get(CAP_PROP_FRAME_COUNT);
	cout << "总共的帧数::" << totalFrameNumber << endl;
	while (true)
	{		
		if (totalFrameNumber == frameNum)			
			break;		
		video >> frame;		
		++frameNum;		
		pMOG2->apply(frame, fgMaskMOG2);
		stringstream ss;
		rectangle(frame, Point(10, 2), Point(100, 20), Scalar(255, 255, 255), -1);
		ss << video.get(CAP_PROP_POS_FRAMES);
		string fameNumberString = ss.str();
		putText(frame, fameNumberString.c_str(), Point(15, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 0));
		imshow("Frame", frame);		
		imshow("FG Mask MOG 2", fgMaskMOG2);
	
		drawRect(fgMaskMOG2, frame);
		keyboard = (char)waitKey(30);
		  
	}
	
	return 0;
}
